﻿using UnityEngine;
using System.Collections;

namespace View
{
    public class ExplosionAnimation
    {

        private int frame = 0;
        private int numberOfFrames;
        private Sprite[] explosionSprites;
        private Texture2D explosionTexture;

        private float radius = 0.5f;
        private Vector2 startPos;
        private Vector2 position;

        private float timeElapsed;
        private float maxTime;

        private int numberOfSpritesX = 4;
        private int numberOfSpritesY = 6;
        private Vector2 spriteSize;

        public ExplosionAnimation(Vector2 startPos, float maxTime, Sprite[] explosionSprites, Texture2D explosionTexture, float ratio)
        {
            timeElapsed = 0.0f;
            this.position = new Vector2(startPos.x, startPos.y);
            this.maxTime = maxTime;
            this.explosionSprites = explosionSprites;
            this.explosionTexture = explosionTexture;
            this.radius *= ratio;


            numberOfFrames = explosionSprites.Length - 1;

            spriteSize = new Vector2(explosionTexture.width / numberOfSpritesX,
                                     explosionTexture.height / numberOfSpritesY);
        }

        private Rect calcTextureRect()
        {
            Rect rect = explosionSprites[frame].rect;
            Rect rectPercent = new Rect(rect.xMin / explosionTexture.width,
                                        rect.yMin / explosionTexture.height,
                                        spriteSize.x / explosionTexture.width,
                                        spriteSize.y / explosionTexture.height);
            return rectPercent;
        }

        // Update is called once per frame
        public void Update()
        {

            if (frame < numberOfFrames)
            {
                timeElapsed += Time.deltaTime;
                float percentAnimated = timeElapsed / maxTime;
                frame = (int)(percentAnimated * numberOfFrames);
            }
            else
            {
                //frame = 0;
                //timeElapsed = 0;
            }
        }

        public void OnGUI(GameCamera cam)
        {
            Vector2 visualPos = cam.getVisualCoordinates(position);
            Vector2 visualSize = cam.getVisualSizeWithRadius(radius);

            GUI.DrawTextureWithTexCoords(new Rect(visualPos.x - visualSize.x / 2, visualPos.y - visualSize.y / 2, visualSize.x, visualSize.y), explosionTexture, calcTextureRect());
        }
    }
}